package com.lzcu.maoyan.maoyanweb.service.impl;

import com.lzcu.maoyan.maoyanweb.mapper.MovieDetailedMapper;
import com.lzcu.maoyan.maoyanweb.pojo.MovieDetailed;
import com.lzcu.maoyan.maoyanweb.service.LoadMovieDetailed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author WangLiang
 * @date `2024/4/22`
 */
@Service
public class LoadMovieDetailedImpl implements LoadMovieDetailed {

    @Autowired
    MovieDetailedMapper movieDetailedMapper;

    @Override
    public void addData() {
        List<String[]> data = loadData();
        for (String[] info : data) {
            if (info.length >= 4){
                MovieDetailed item = new MovieDetailed(info[0],info[1],info[2],info[3]);
                movieDetailedMapper.insertData(item);
            }
        }
    }

    @Override
    public Map<String, Object> queryName(String name) {
        MovieDetailed movieDetailed = movieDetailedMapper.selectName(name);

        return null;
    }

    private List<String[]> loadData(){
        List<String[]> data = new ArrayList<>();
        ClassPathResource classPathResource = new ClassPathResource("movieLib.csv");
        try (InputStream inputStream = classPathResource.getInputStream()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] values = line.split(",");
                data.add(values);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
